<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>背点八股文 - 登录</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-container {
            max-width: 400px;
            width: 100%;
            padding: 20px;
        }
        .card {
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .card-header {
            background-color: #007bff;
            color: white;
            font-weight: bold;
            padding: 1rem;
        }
        .tab-content {
            padding: 20px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .nav-tabs .nav-link {
            border: none;
            color: #495057;
        }
        .nav-tabs .nav-link.active {
            color: #007bff;
            background-color: transparent;
            border-bottom: 2px solid #007bff;
        }
        #toast {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div id="toast"></div>
        
        <div class="card">
            <div class="card-header text-center">
                <h4 class="mb-0">背点八股文</h4>
            </div>
            <div class="card-body">
                <ul class="nav nav-tabs" id="myTab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <a class="nav-link active" id="login-tab" data-toggle="tab" href="#login" role="tab" aria-controls="login" aria-selected="true">登录</a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" id="register-tab" data-toggle="tab" href="#register" role="tab" aria-controls="register" aria-selected="false">注册</a>
                    </li>
                </ul>
                <div class="tab-content" id="myTabContent">
                    <!-- 登录表单 -->
                    <div class="tab-pane fade show active" id="login" role="tabpanel" aria-labelledby="login-tab">
                        <form id="loginForm">
                            <div class="form-group">
                                <label for="loginUsername">用户名</label>
                                <input type="text" class="form-control" id="loginUsername" required>
                            </div>
                            <div class="form-group">
                                <label for="loginPassword">密码</label>
                                <input type="password" class="form-control" id="loginPassword" required>
                            </div>
                            <button type="submit" class="btn btn-primary btn-block">登录</button>
                        </form>
                    </div>
                    
                    <!-- 注册表单 -->
                    <div class="tab-pane fade" id="register" role="tabpanel" aria-labelledby="register-tab">
                        <form id="registerForm">
                            <div class="form-group">
                                <label for="registerUsername">用户名</label>
                                <input type="text" class="form-control" id="registerUsername" required>
                                <small class="form-text text-muted">用户名长度为4-20个字符</small>
                            </div>
                            <div class="form-group">
                                <label for="registerPassword">密码</label>
                                <input type="password" class="form-control" id="registerPassword" required>
                                <small class="form-text text-muted">密码长度为6-20个字符</small>
                            </div>
                            <div class="form-group">
                                <label for="registerNickname">昵称</label>
                                <input type="text" class="form-control" id="registerNickname" required>
                            </div>
                            <button type="submit" class="btn btn-primary btn-block">注册</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // 如果已登录，直接跳转到首页
            const token = localStorage.getItem('token');
            if (token) {
                validateToken(token);
            }
            
            // 登录表单提交
            $("#loginForm").on("submit", function(e) {
                e.preventDefault();
                
                // 获取表单数据
                const username = $("#loginUsername").val().trim();
                const password = $("#loginPassword").val().trim();
                
                if (!username || !password) {
                    showToast("用户名和密码不能为空", "warning");
                    return;
                }
                
                // 创建登录数据对象
                const loginData = {
                    username: username,
                    password: password
                };
                
                console.log("发送登录请求...");
                console.log("登录数据:", loginData);
                
                // 发送登录请求
                $.ajax({
                    url: "/api/user/login",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(loginData),
                    success: function(response) {
                        console.log("登录响应:", response);
                        
                        if (response.code === 200) {
                            showToast("登录成功", "success");
                            
                            // 保存token和用户信息
                            localStorage.setItem('token', response.data.token);
                            localStorage.setItem('username', response.data.username);
                            localStorage.setItem('nickname', response.data.nickname);
                            localStorage.setItem('userId', response.data.id);
                            
                            // 跳转到首页
                            setTimeout(function() {
                                window.location.href = "/index.html";
                            }, 1000);
                        } else {
                            showToast("登录失败: " + response.message, "danger");
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("登录错误:", error);
                        console.error("状态:", status);
                        console.error("响应:", xhr.responseText);
                        
                        let message = "登录失败";
                        if (xhr.responseJSON) {
                            message += ": " + xhr.responseJSON.message;
                        }
                        showToast(message, "danger");
                    }
                });
            });
            
            // 注册表单提交
            $("#registerForm").on("submit", function(e) {
                e.preventDefault();
                
                const username = $("#registerUsername").val().trim();
                const password = $("#registerPassword").val().trim();
                const nickname = $("#registerNickname").val().trim();
                
                // 验证表单
                if (!username || !password || !nickname) {
                    showToast("所有字段都必须填写", "warning");
                    return;
                }
                
                // 验证用户名和密码长度
                if (username.length < 4 || username.length > 20) {
                    showToast("用户名长度必须在4-20之间", "warning");
                    return;
                }
                
                if (password.length < 6 || password.length > 20) {
                    showToast("密码长度必须在6-20之间", "warning");
                    return;
                }
                
                // 创建注册数据对象
                const registerData = {
                    username: username,
                    password: password,
                    nickname: nickname
                };
                
                console.log("发送注册请求...");
                console.log("注册数据:", registerData);
                
                // 发送注册请求
                $.ajax({
                    url: "/api/user/register",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(registerData),
                    success: function(response) {
                        console.log("注册响应:", response);
                        
                        if (response.code === 200) {
                            showToast("注册成功，即将跳转到首页", "success");
                            
                            // 保存token和用户信息
                            localStorage.setItem('token', response.data.token);
                            localStorage.setItem('username', response.data.username);
                            localStorage.setItem('nickname', response.data.nickname);
                            localStorage.setItem('userId', response.data.id);
                            
                            // 跳转到首页
                            setTimeout(function() {
                                window.location.href = "/index.html";
                            }, 1500);
                        } else {
                            showToast("注册失败: " + response.message, "danger");
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("注册错误:", error);
                        console.error("状态:", status);
                        console.error("响应:", xhr.responseText);
                        
                        let message = "注册失败";
                        if (xhr.responseJSON) {
                            message += ": " + xhr.responseJSON.message;
                        }
                        showToast(message, "danger");
                    }
                });
            });
            
            // 验证token
            function validateToken(token) {
                if (!token) return;
                
                $.ajax({
                    url: "/api/user/current",
                    type: "GET",
                    headers: {
                        "Authorization": "Bearer " + token
                    },
                    success: function(response) {
                        console.log("验证token响应:", response);
                        
                        if (response.code === 200) {
                            // token有效，跳转到首页
                            window.location.href = "/index.html";
                        } else {
                            // token无效，清除localStorage
                            clearLocalStorage();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("验证token错误:", error);
                        // 请求出错，清除localStorage
                        clearLocalStorage();
                    }
                });
            }
            
            // 清除本地存储
            function clearLocalStorage() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                localStorage.removeItem('nickname');
                localStorage.removeItem('userId');
            }
            
            // 显示提示框
            function showToast(message, type) {
                console.log(type + ": " + message);
                
                const toast = $(`
                    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000">
                        <div class="toast-header bg-${type} text-white">
                            <strong class="mr-auto">提示</strong>
                            <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="toast-body">${message}</div>
                    </div>
                `);
                
                $("#toast").append(toast);
                toast.toast("show");
                
                // 自动删除
                setTimeout(function() {
                    toast.remove();
                }, 3000);
            }
        });
    </script>
</body>
</html> 